######################
#  Replication code for 'Mediating the Electoral Connection', forthcoming in the JOP
#  John Henderson and John Brooks
#  12/7/2015    
######################    

# imputeCovs.R
#  :: runs data imputation to build from <rain_data>
#     covs_all, covs_some, covs_none
   
# Notes: produces outcomes from rain_data following non.missings = 4; 
#  -- this is using icpsr links to identify prior values for variables
#    note this is somewhat distinct from non.missings = 0; 
#    which uses district*state indicators + incumbency variables to identify prior values

rm(list=ls())
setwd('~/Dropbox/rainReplication')

load('buildData/RainData.Rdata')

rain_data$comp_cq[which(rain_data$comp_cq<0)]=NA      

dem_shr=rain_data$dem_shr
rep_shr=rain_data$rep_shr
dem_prv=dem_shr[rain_data$prior_obs]
rep_prv=rep_shr[rain_data$prior_obs]

dose=dem_shr-rep_shr
dose_prv=dem_prv-rep_prv

vote=rain_data$y_shr	
vote_prv=vote[rain_data$prior_obs]	
vote[which(rain_data$d_inc==1 & rain_data$d_win==0)]=vote_prv[which(rain_data$d_inc==1 & rain_data$d_win==0)]
vote[which(rain_data$r_inc==1 & rain_data$r_win==0)]=vote_prv[which(rain_data$r_inc==1 & rain_data$r_win==0)]	
		
ix=which(rain_data$d_inc==1 & rain_data$d_win==0 & dose>0)
dose[ix]=NA
dose_prv[ix]=NA                                           
ix=which(rain_data$d_inc==1 & rain_data$d_win==1 & dose<0)
dose[ix]=NA      
dose_prv[ix]=NA                                           
ix=which(rain_data$r_inc==1 & rain_data$r_win==0 & dose<0)
dose[ix]=NA     
dose_prv[ix]=NA                                           
ix=which(rain_data$r_inc==1 & rain_data$r_win==1 & dose>0)
dose[ix]=NA   
dose_prv[ix]=NA
       

covs=cbind(dose,dose_prv,vote,vote_prv,
	rain_data[,c('rain_day','rain_day_prev','rain_weekend','rain_weekend_prev',
				 'd_inc','dist_prev','comp_cq','redistricted','sos','gov','midterm','pres_party',
				 'minc','pop','black','construction','educ','farmer','forborn','gvtwkr',
				 'manuf','unempld','urban','retail')])
                                      
if(length(which(installed.packages()[,1]=='mice'))!=1){
	install.packages('mice')                        
}          

library(mice)      
set.seed(1005)
m.impute=mice(covs,m=5)  
     
covs_all=covs_some=covs_none=covs
covs_part=list()                           
for(i in 1:5){
	covs_part[[i]]=complete(m.impute,action=i)                
}
     
for(j in 1:ncol(covs)){
	covs_all[,j]=rowMeans(cbind(covs_part[[1]][,j],covs_part[[2]][,j],covs_part[[3]][,j],covs_part[[4]][,j],covs_part[[5]][,j]))
}   

covs_some=covs_all
covs_some[,c(1:8)]=covs_none[,c(1:8)]  

covs_some$comp_cq=round(covs_some$comp_cq)
covs_all$comp_cq=round(covs_all$comp_cq)
covs_none$comp_cq=round(covs_none$comp_cq)
             
save(covs_none,covs_some,covs_all,
	file='buildData/RainRepresentation.Rdata')

save(rain_data,covs_all,covs_some,covs_none,
	file='FinalRainData.Rdata')
            
# END